package com.chii.color.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chii.color.client.ImageClient;
import com.chii.color.client.UserClient;
import com.chii.color.config.MQConfig;
import com.chii.color.po.ColorHistory;
import com.chii.color.service.HistoryService;
import com.chii.color.service.UploadSevice;
import com.chii.color.utils.OkHttpHelp;
import com.chii.color.utils.RedisUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.UUID;
@Component
public class UploadServiceImpl implements UploadSevice {
    @Value("${localhost.python}")
    private String pythonHost;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private HistoryService historyService;
    @Resource
    private ImageClient imageClient;
    @PostConstruct
    private void initRedis() {
        if (!redisUtil.hasKey("MQCount")) {
            redisUtil.set("MQCount", 0);
        }
    }
    @Override
    public void upload(JSONObject msg) throws IOException {
        int uid = msg.getInteger("uid");
        String fileName = msg.getString("fileName");
        String inFile = msg.getString("inFile");
        String renderFactor = msg.getString("render_factor");
        File temp = (File) msg.get("file");

        //使用python翻译图片
        HashMap<String, String> map = new HashMap<>();
        map.put("render_factor", renderFactor);
        JSONObject callBack = new OkHttpHelp().postImage(pythonHost, map, temp);
        String base64 = callBack.getString("img_base64");
        //保存图片qiniu
        String outFile = imageClient.updateBase64Image(base64, fileName + "-output.jpg", "qiniu").getData();
        //加入历史记录数据库
        ColorHistory history = historyService.insertNewHistory(uid, inFile, outFile);
        //删除临时文件temp
        temp.delete();

        redisUtil.decr("MQCount", 1);
    }

}
